﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace AbacusCustom
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        public int validate_login(String username, String password)
        {
            Module db_conf = new Module();

            int statement = 0;

            SqlConnection conn = new SqlConnection();
            conn.ConnectionString =
            "Data Source=" + db_conf.db_host + ";" +
            "Database=PSCUSTOM;"+
            "User ID=" + db_conf.db_user + ";" +
            "Password=" + db_conf.db_password + ";";
            conn.Open();

            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT ID,username FROM PS_ACCOUNT WHERE USERNAME = '"+username+"' AND PASSWORD = '"+password+"'";

            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                if (reader.GetString(1).Equals(username))
                {
                    statement = reader.GetInt32(0);
                }
            }
            conn.Close();

            return statement;
        }

        public void refresh_form()
        {
            txtUsername.Text = "";
            txtPassword.Text = "";
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            refresh_form();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            refresh_form();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                int a = validate_login(txtUsername.Text, txtPassword.Text);
                if (a > 0)
                {
                    Module.session_username = txtUsername.Text;
                    Module.session_userid = a.ToString();
                    this.Hide();
                    frmAbacusCustom fac = new frmAbacusCustom();
                    fac.Show();

                }
                else
                {
                    MessageBox.Show("Either username or password is incorrect","Information");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("You're not connected to the server, please check your connection", "Information");
            }
        }
    }
}
